package com.zjw.touchscreen.listener;

import android.annotation.SuppressLint;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;
import com.zjw.touchscreen.bluetooth.MouseHelper;

import java.util.LinkedList;

@SuppressLint("NewApi")
public class TouchTopListener implements View.OnTouchListener {

    private SeekBar seekBar;
    private float x = 0;

    private LinkedList<Float> offsetList = new LinkedList<>();

    public TouchTopListener(SeekBar seekBar) {
        this.seekBar = seekBar;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                move(event);
                break;
            case MotionEvent.ACTION_UP:
                MouseHelper.sendData(false, false, false, 0, 0, 0);
                for (Float xOffset : offsetList) {
                    MouseHelper.sendData(false, false, false, (int) (xOffset * -1), 0, 0);
                }
                offsetList.clear();
                break;
        }
        return true;
    }

    private void move(MotionEvent event) {
        int speed = seekBar.getProgress();
        float xOffset = event.getX() - x;
        x = event.getX();
        xOffset = xOffset * speed > 127 ? 127 : xOffset * speed;
        xOffset = xOffset * speed < -127 ? -127 : xOffset * speed;
        if(xOffset==0){
            return;
        }
        offsetList.push(xOffset);
        MouseHelper.sendData(true, false, false, (int) xOffset, 0, 0);
    }
}
